<template>
  <div class="app-container">
    <el-container style="height: 750px; border: 1px solid #eee">
      <el-aside width="200px" style="background-color: rgb(238, 241, 246)">
        <h5>审批类型</h5>

        <el-menu
          :default-active="defaultActive"
          unique-opened
          @select="handleSelect"
          class="el-menu-vertical-demo"
        >

          <div v-for="item in treeList" :key="item.code">
            <el-submenu :index="item.code">
              <template v-slot="title">
                <span>{{ item.name }}</span>
              </template>
              <!-- 这里循环的就是 children 里面的数据 -->
              <el-menu-item v-for="val in item.children" :index="val.code" :key="val.code">{{ val.name }}</el-menu-item>
            </el-submenu>
          </div>
        </el-menu>
      </el-aside>
      <el-container>
        <el-header style="text-align: left; height: 80px; font-size: 12px">
          <h3>基本信息</h3>
          <el-form :inline="true">
            <el-form-item label="归属公司：" prop="compId">
              <el-select ref="selComp" v-model="compId" filterable placeholder="请选择公司">
                <el-option
                  v-for="item in compList"
                  :key="item.compId"
                  :label="item.compName"
                  :value="item.compId"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="流程名称：" prop="ruleName">
              <el-input v-model="ruleName" placeholder="请输流程名称"/>
            </el-form-item>
            <el-form-item label="规则类型：" prop="auditType">
              <el-select ref="selAudit" v-model="auditType" filterable placeholder="请选择类型">
                <el-option
                  v-for="item in audits"
                  :key="item.code"
                  :label="item.name"
                  :value="item.code"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-form>
        </el-header>

        <el-main style="text-align: left; font-size: 12px">
          <h3>流程配置</h3>
          <el-container style="height: 500px; width: 1000px; border: 1px solid #eee">
            <el-aside width="300px" style="background-color: rgb(238, 241, 246)">
              <h4>提交审批环节设定</h4>
              <el-tabs v-model="activeName">
                <el-tab-pane label="部门" name="dept">
                  <el-input size="small" v-model="filterD" placeholder="请输入部门">
                    <i slot="prefix" class="el-input__icon el-icon-search"></i>
                  </el-input>
                  <el-tree
                    :props="treeProps"
                    :data="this.deptTree"
                    show-checkbox
                    default-expand-all
                    ref="treeD"
                    node-key="id"
                    :filter-node-method="filterDept"
                    @check="handleCheck"
                  >
                  </el-tree>
                </el-tab-pane>
                <el-tab-pane label="提审人" name="referee">
                  <el-input size="small" v-model="filterU" prefix-icon="el-icon-search" placeholder="请输入提审人"/>
                  <el-table
                    ref="refereeRen"
                    @selection-change="refereeSelection"
                    :data="userTree"
                  >
                    <el-table-column type="selection"/>
                    <el-table-column prop="id" label="ID" align="center"/>
                    <el-table-column prop="name" label="名称" align="center"/>
                  </el-table>
                </el-tab-pane>
              </el-tabs>
            </el-aside>

            <el-transfer
              style="text-align: left; display: inline-block"
              v-model="valueU"
              filterable
              ref="transferR"
              :props="{ key: 'id', label: 'name' }"
              :render-content="renderFunc"
              :titles="['审批人配置环节', '审批人层级审定']"
              :button-texts="['', '']"
              target-order="push"
              :format="{ noChecked: '${total}', hasChecked: '${checked}/${total}' }"
              @change="approvalSel"
              :data="approvalUser"
            >
            </el-transfer>
          </el-container>
        </el-main>
        <el-main style="text-align: center; font-size: 12px">
          <el-button @click="$router.push('/tool/approval')">返回</el-button>
          <el-button type="primary" @click="saveOrEdit">保存</el-button>
        </el-main>
      </el-container>
    </el-container>

  </div>
</template>
<style>
.el-transfer-panel {
  width: 255px;
}

.el-transfer-panel__body {
  height: 440px;
}
</style>
<script>
import api from '@/api/tool/approval'
// import Sortable from 'sortablejs'

export default {
  name: 'AddOrEdit',
  data() {
    return {
      ruleId: '',
      ruleNo: '',
      defaultActive: '01-03',

      compList: [],

      audits: [],

      treeList: [],
      activeName: 'dept',

      treeProps: { key: 'id', label: 'name' },
      deptTree: [],
      roleTree: [],
      userTree: [],

      filterD: '',
      filterU: '',

      approvalUser: [],

      // 审批模块
      approvalModule: '01',
      // 规则大类
      ruleClass: '03',
      // 公司名称
      compName: '',
      compId: '',
      // 规则名称
      ruleName: '',
      // 类型
      auditType: '',
      // 提交部门
      subDept: [],
      // 提交人
      subRen: [],
      // 审批人
      approvalRen: [],
      renderFunc(h, option) {
        return <span>{option.id} - {option.name}</span>
      },
      valueU: []
    }
  },
  mounted() {
  },
  created() {
    this.fetchData()
    this.getDeptRoleUser()
  },
  watch: {
    filterD(val) {
      this.$refs.treeD.filter(val)
    },
    filterU: function(val, oldVal) {
      this.userTree = this.approvalUser.filter(item => (~item.name.indexOf(val)))
      // TODO 重新过滤时会把之前勾选冲掉，所以要把之前选中的重新勾上 参考 pending.vue的操作
      // 大概思路：进页面时把用户列表给二个数组存着a,b，列表的data用b，过滤用@input事件
      // 过滤时用a数组去过滤关键字,把过滤的结果重新赋给b,同时过滤后对比选中数据中有没有过滤的，有就设置勾选
      // 每次勾选数据时记得不直接赋值给selectData(没筛选可直接赋值)，要判断勾选数据在不在其中，不在用push()进去
      // 因为过滤问题，每次都是从b中赋值给selectData，会把之前已勾数据冲掉
      this.reselectData()
    }
    // userTree() {
    //
    // }
  },
  methods: {
    reselectData() {
      // 重新勾选 之前勾选的数据
      const newData = this.subRen.filter(item => this.userTree.includes(item))
      this.$nextTick(() => {
        if (Array.isArray(newData)) {
          newData.forEach(item => {
            const index = this.userTree.indexOf(item)
            if (index >= 0) {
              this.$refs.refereeRen.toggleRowSelection(this.userTree[index], true)
            }
          })
        } else {
          const index = this.userTree.indexOf(newData)
          if (index >= 0) {
            this.$refs.refereeRen.toggleRowSelection(this.userTree[index], true)
          }
        }
      })
    },
    fetchData() {
      api.getRuleEnum().then(res => {
        if (res.code === 200) {
          this.treeList = res.data
          // 初始时给个默认值
          const modes = this.treeList.filter(e => e.code === '01')[0]
          this.audits = modes.children.filter(e => e.code === '01-03')[0].children
        } else {
          this.$message.error('查询规则类型失败!')
        }
      })
      api.getCompList().then(res => {
        if (res.code === 200) {
          this.compList = res.data
        } else {
          this.$message.error('查询公司失败!')
        }
      })
    },

    getDeptRoleUser() {
      api.getDeptRoleUser().then(res => {
        if (res.code === 200) {
          this.deptTree = res.data.deptList
          this.roleTree = res.data.roleList
          this.userTree = res.data.userList
          this.approvalUser = res.data.userList
          // 数据加完后进行勾选赋值
          this.assignment()
        } else {
          this.$message.error('查询失败!')
        }
      })
    },
    assignment() {
      const ruleId = this.$route.query.ruleId
      if (ruleId) {
        api.details(ruleId).then(res => {
          this.ruleId = res.data.ruleId
          this.ruleNo = res.data.ruleNo
          this.approvalModule = res.data.approvalModule
          this.ruleClass = res.data.ruleClass
          this.auditType = res.data.auditType
          this.defaultActive = this.approvalModule + '-' + this.ruleClass

          const modes = this.treeList.filter(e => e.code === this.approvalModule)
          this.audits = modes[0].children.filter(e => e.code === this.defaultActive)[0].children

          this.compId = res.data.compId
          this.compName = res.data.compName
          this.ruleName = res.data.ruleName
          const subRenR = res.data.subRen
          if (subRenR && subRenR.length > 0) {
            for (let i = 0; i < this.userTree.length; i++) {
              if (subRenR.includes(this.userTree[i].id)) {
                // 选中提交人
                this.$refs.refereeRen.toggleRowSelection(this.userTree[i], true)
                this.subRen.push(this.userTree[i])
              }
            }
          }

          this.subDept = res.data.subDept
          if (this.subDept && this.subDept.length > 0) {
            // 选中提交部门
            this.$refs.treeD.setCheckedKeys(this.subDept)
          }

          this.valueU = res.data.approvalRen
        })
      }
    },
    filterDept(value, data) {
      if (!value) return true
      return data.name.indexOf(value) !== -1
    },
    handleCheck(val, checkDept) {
      this.subDept = checkDept.checkedKeys
    },
    refereeSelection(sel) {
      if (sel.length === 0) {
        this.userTree.forEach(e => {
          const index = this.subRen.findIndex(item => item.id === e.id)
          if (index >= 0) {
            this.subRen.splice(index, 1)
          }
        })
      } else {
        const notCu = []
        // 从过滤数据中找出没勾选的数据
        this.userTree.forEach(e => {
          const index = sel.findIndex(item => item.id !== e.id)
          if (index >= 0) {
            notCu.push(e)
          }
        })
        // 把没勾选的从 总集合中删除
        notCu.forEach(ee => {
          const index = this.subRen.findIndex(item => item.id === ee.id)
          if (index >= 0) {
            this.subRen.splice(index, 1)
          }
        })
        // 在把新勾选的添加到总集合
        sel.forEach(item => {
          if (!this.subRen.includes(item)) {
            this.subRen.push(item)
          }
        })
      }
      console.log('提交人>', this.subRen)
    },
    approvalSel(value, direction, movedKeys) {
      if (this.approvalRen) this.approvalRen = []
      this.approvalRen = value
    },
    handleSelect(e, p) {
      // if (this.selectMu) this.selectMu = []
      this.approvalModule = p[0]
      this.ruleClass = p[1]
      this.auditType = ''
      // 根据根据大类过滤出小类填充
      const modes = this.treeList.filter(e => e.code === this.approvalModule)[0]
      this.audits = modes.children.filter(e => e.code === this.ruleClass)[0].children
    },

    saveOrEdit() {
      // 左侧审批模块和规则大类
      // const sel = this.selectMu
      if (!this.approvalModule || !this.ruleClass) {
        this.$message.error('规则大类不能为空!')
        return
      }

      // 基本信息
      const compId = this.compId
      const rule = this.ruleName
      if (!compId || !rule) {
        this.$message.error('基本信息不能为空!')
        return
      }

      // 流程配置 提交部门和人
      const subDept = this.subDept === undefined ? [] : this.subDept
      const subRen = this.subRen === undefined ? [] : Array.from(new Set(this.subRen.map(e => e.id)))
      if (subDept.length === 0 && subRen.length === 0) {
        this.$message.error('提交部门或人不能为空!')
        return
      }

      // 审批人
      let appRen = this.approvalRen
      const params = {
        compId: compId,
        compName: this.$refs.selComp.selectedLabel,
        ruleName: rule,
        ruleNo: this.ruleNo,
        approvalModule: this.approvalModule,
        ruleClass: this.ruleClass,
        auditType: this.$refs.selAudit.value,
        subDept: subDept,
        subRen: subRen,
        approvalRen: appRen
      }

      if (Object.keys(appRen).length === 0) {
        appRen = this.valueU
        if (Object.keys(appRen).length === 0) {
          this.$confirm('不配置审批人,系统会自动审批,确认吗?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.subSave(params)
          }).catch(() => {
            return
          })
        } else {
          params.approvalRen = appRen
          this.subSave(params)
        }
      } else {
        this.subSave(params)
      }
    },

    subSave(params) {
      if (this.ruleId) {
        params.ruleId = this.ruleId
        api.updateRule(params).then(res => {
          if (res.code === 200) {
            this.$confirm('修改成功,是否跳转列表页面?', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              this.$router.push('/tool/approval')
            }).catch(() => {
            })
          }
        })
      } else {
        api.addRule(params).then(res => {
          if (res.code === 200) {
            this.$confirm('新增成功,是否跳转列表页面?', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              this.$router.push('/tool/approval')
            }).catch(() => {
            })
          }
        })
      }
    }

  }
}
</script>

